import md5 from 'js-md5';
import Qs from 'qs';
import { downloadFile } from '@/api/public';
import dayjs from 'dayjs';
import MQTT from '@/framework/utils/mqtt';
import { icBoxId } from '@/api/utils';
/**
 * 给请求头添加Md5
 */
export const getMd5 = (options, header) => {
  if (header === 'application/json;charset=UTF-8') {
    let str = '{';
    let keys: any[] = [];
    if (options.params) {
      keys = Qs.stringify(options.params, { arrayFormat: 'indices', allowDots: true }).split('&').sort();
    } else if (options.url.indexOf('?') !== -1) {
      const urlParams = options.url.split('?')[1];
      keys.push(...urlParams.split('&'));
      keys = keys.sort();
    }
    keys.forEach((x: any) => {
      const tempArr = x.split('=');
      str += '"' + decodeURIComponent(tempArr[0]) + '":["' + decodeURIComponent(tempArr[1]) + '"],';
    });
    if (keys.length > 0) {
      str = str.substr(0, str.length - 1);
    }
    str += '}';
    if (options.data) {
      str += JSON.stringify(options.data);
    }
    str = 'HCCX' + options.url + str + 'BIMS';
    // console.log(str)
    return md5(str);
  } else if (header === 'application/x-www-from-urlencoded') {
    // let ParamsKeys = Qs.stringify(options.params, { arrayFormat: 'indices', allowDots: true }).split('&')
    // let DataKeys = options.data.split('&')
    let NewParams = options.data.split('&');
    // let NewParams = [...ParamsKeys, ...DataKeys]
    NewParams = NewParams.sort();
    let str1 = '{';
    NewParams.forEach((x) => {
      const tempArr = x.split('=');
      str1 += '"' + decodeURIComponent(tempArr[0]) + '":["' + decodeURIComponent(tempArr[1]) + '"],';
    });
    if (NewParams.length > 0) {
      str1 = str1.substr(0, str1.length - 1);
    }
    str1 += '}';
    str1 = 'HCCX' + str1 + 'BIMS';
    return md5(str1);
  }
};

// 把下标转换成位置
export const subscript = (sortIndex, row) => {
  let one = Math.ceil((sortIndex + 1) / row);
  let two = sortIndex + 1 - (one - 1) * row;
  return one + '-' + two;
};

// md5转图片
export const getImageFn = async (md5) => {
  const res = await downloadFile(md5);
  const bufferUrl = btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''));
  return 'data:image/png;base64,' + bufferUrl;
};
//给已经有扩展字段的数据把样本类型筛选出来添加上
export const addSpecimenType = (res) => {
  res.forEach((item) => {
    item.sampleTime ? (item.sampleTime = dayjs(item.sampleTime).format('YYYY-MM-DD')) : '';
    if (item?.unit == 1) item.newcapacity = `${item?.capacity ? item?.capacity : 0}ml`;
    if (item?.unit == 2) item.newcapacity = `${item?.capacity ? item?.capacity : 0}μl`;
    if (item?.extDataList) {
      item.extDataList.forEach((el) => {
        if (el.key == 'specimen_type') {
          item[el.key] = el.value;
        }
      });
    }
  });
};
//把数据处理成平板需要的数据然后推出去
export const padData = async (data, id, type) => {
  let taskinfo: any = [];
  for (let i = 0; i < data.length; i++) {
    data[i].serialId ? '' : (data[i].serialId = data[i].storageId);
    let { result } = await icBoxId(data[i].serialId);
    data[i].storageId = result.find((item) => item.type == 2).id;
  }
  data.forEach((item) => {
    let taskTemplist: any = [];
    let arr = item.list ? item.list : item.subSpecimens;
    arr.forEach((el) => {
      taskTemplist.push({
        originalSerial: el.originalSerial,
        serial: el.serial,
        name: el.name,
        position: el.seat,
        sortIndex: el.sortIndex,
        storageId: item.storageId,
        storageDesp: el.storageDesp,
      });
    });
    taskinfo.push({
      taskinfo: {
        taskType: type,
        cautionTime: '',
        userName: '',
        batchNo: id,
        operatorName: '',
        outputtype: 0,
        serial: item.serial,
        cols: item?.boxCols ? item.boxCols : item?.cols,
        rows: item?.boxRows ? item.boxRows : item?.rows,
        taskDetail: taskTemplist,
      },
    });
  });
  let taskList = JSON.stringify(taskinfo);
  MQTT.publish('bims/pad/share/taskpush', '{"on":true,"taskList":' + taskList + '}');
};
//把盘点的数据处理成平板需要的数据然后推出去
export const padDataInventory = async (data, countData, type) => {
  let taskinfo: any = [];
  for (let i = 0; i < data.length; i++) {
    data[i].serialId ? '' : (data[i].serialId = data[i].storageId);
    let { result } = await icBoxId(data[i].serialId);
    data[i].storageId = result.find((item) => item.type == 2).id;
  }

  data.forEach((item) => {
    let taskTemplist: any = [];
    let arr = item.list ? item.list : item.subSpecimens;
    arr.forEach((el) => {
      taskTemplist.push({
        originalSerial: el.originalSerial,
        serial: el.serial,
        name: el.name,
        position: el.seat,
        sortIndex: el.sortIndex,
        storageId: item.storageId, //冰箱ID
        storageDesp: el.storageDesp, // 存储位置
        checktype: '按盒盘点',
        type: '保藏样本',
      });
    });
    taskinfo.push({
      taskinfo: {
        taskType: type,
        name: countData.name, // 盘点单名称
        inventoryType: countData.type == 2 ? '按样本盒抽检' : '全检', // 订单盘点方式
        batchNo: countData.batchNo,
        outputtype: 0,
        cols: item?.boxCols ? item.boxCols : item?.cols,
        rows: item?.boxRows ? item.boxRows : item?.rows,
        taskDetail: taskTemplist,
      },
    });
  });
  let taskList = JSON.stringify(taskinfo);
  MQTT.publish('bims/pad/share/taskpush', '{"on":true,"taskList":' + taskList + '}');
};

export const sliceStr = (str, num) => {
  if (!str) return '-';
  str = String(str);
  if (str.length > num) {
    return str.slice(0, num) + '...';
  }
  return str;
};

export const unitCheck = (value, unit: 1 | 2 | 'ml' | 'μl') => {
  if (typeof unit === 'number') {
    switch (unit) {
      case 1:
        unit = 'ml';
        break;
      case 2:
        unit = 'μl';
        break;
    }
  }
  return `${value}${unit ?? ''}`;
};
